import { Message } from 'element-ui'
import { resetRouter } from '@/router/index'
import UserApi from '@/api/user'
import Auth from '@/utils/auth'
import Cookies from 'js-cookie'

const state = {
  roles: null,
  token: null
}

const mutations = {
  setToken (state, token) {
    state.token = token
  },
  setRoles (state, roles) {
    state.roles = roles
  }
}

const actions = {
  // 用户登录
  login ({ commit }, userInfo) {
    const { username: login_name, password: login_password } = userInfo
    return new Promise((resolve, reject) => {
      UserApi.login({ user_name: login_name.trim(), password: login_password })
        .then(res => {
          if (Number(res.errno) === 0) {
            commit('setToken', res.data.token)
            Cookies.set('game_id', res.data.zong_dai_info.game_id)
            Cookies.set('user_name', res.data.zong_dai_info.user_name)
            Auth.setToken(res.data.token)
            resolve()
          } else {
            Message({
              message: res.errmsg || 'Error',
              type: 'error',
              duration: 5 * 1000
            })
            reject(res)
          }
        })
        .catch(err => reject(err))
    })
  },
  // 获取用户信息
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      UserApi.getInfo({ token: state.token, game_id: 8, resource_key: 'clubopapisrv' })
        .then(res => {
          if (res.errno !== 0) {
            reject(new Error('Verification failed, please Login again.'))
          }
          const { permission: roles } = res
          // roles must be a int number
          if (!Number(roles)) {
            reject(new Error('getInfo: roles must be a int number!'))
          }
          commit('setRoles', roles)
          resolve(roles)
        })
        .catch(err => reject(err))
    })
  },
  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit('setToken', null)
      commit('setRoles', null)
      Auth.removeToken()
      resolve()
    })
  },
  logout ({ commit }) {
    return new Promise(resolve => {
      commit('setToken', null)
      commit('setRoles', null)
      Auth.removeToken()
      resetRouter()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
